#include "gtrack_list.h"

void gtrack_listInit(GTrack_ListObj* list)
{
	/* 初始化列表对象中的字段 */
	list->count = 0;
	list->begin = 0;
	list->end = 0;
}

int32_t gtrack_isListEmpty(GTrack_ListObj* list)
{
	if (list->count == 0)
		return 1;
	return 0;
}

void gtrack_listEnqueue(GTrack_ListObj* list, GTrack_ListElem* elem)
{
    if (list->begin == 0)
    {
        elem->prev = 0;
        elem->next = 0;

        list->begin = elem;
        list->end = elem;
    }
    else
    {
        elem->prev = list->end;
        elem->next = 0;

        list->end->next = elem;
        list->end = elem;
    }
    list->count++;
}

GTrack_ListElem* gtrack_listDequeue(GTrack_ListObj* list)
{
    GTrack_ListElem* elem;

    if (list->begin == 0)
        return 0;

    elem = list->begin;
    list->begin = elem->next;
    list->count--;

    if (list->begin == 0)
        list->end = 0;

    elem->next = 0;
    elem->prev = 0;

    return elem;
}

GTrack_ListElem* gtrack_listGetFirst(GTrack_ListObj* list)
{
    return list->begin;
}

GTrack_ListElem* gtrack_listGetNext(GTrack_ListElem* elem)
{
    return elem->next;
}

uint32_t gtrack_listGetCount(GTrack_ListObj* list)
{
    return list->count;
}

int32_t gtrack_listRemoveElement(GTrack_ListObj* list, GTrack_ListElem* elem)
{
    if (elem->prev == 0)
    {
        if (list->begin != elem)
            return -1;

        if (elem->next == 0)
        {
            /* 只有当下一个元素是最后一个元素时，下一个元素才可能是 NULL */
            if (list->end != elem)
                return -1;

            if (list->count != 1)
                return -1;

            /* 该元素是唯一的元素，现在列表为空 */
            list->begin = 0;
            list->end = 0;
            list->count = 0;
            return 0;
        }

        if (elem->next->prev != elem)
            return -1;

        /* 该元素是第一个元素，更新列表begin */
        list->begin = elem->next;
        elem->next->prev = 0;
        list->count--;
        return 0;
    }

    if (elem->prev->next != elem)
        return -1;

    if (elem->next == 0)
    {
        /* 只有当下一个元素是最后一个元素时，下一个元素才可能是 NULL */
        if (list->end != elem)
            return -1;

        /* Yes, it is valid last element */
        elem->prev->next = 0;
        list->end = elem->prev;
        list->count--;
        return 0;
    }

    if (elem->next->prev != elem)
        return -1;

    elem->prev->next = elem->next;
    elem->next->prev = elem->prev;
    list->count--;
    return 0;
}
